import fs from 'fs-extra';
import path from 'path';
import Epub from 'epub-gen';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export async function convertTxtToEpub(txtFilePath) {
    try {
        // 确保文件路径是绝对路径
        txtFilePath = path.resolve(txtFilePath);
        console.log('输入文件路径:', txtFilePath);

        // 读取TXT文件
        const content = await fs.readFile(txtFilePath, 'utf-8');
        console.log('文件内容长度:', content.length);
        
        // 解析章节
        const chapters = [];
        const chapterRegex = /第(\d+)章\s+([^\n]+)\n\n([\s\S]*?)(?=第\d+章|$)/g;
        let match;
        
        while ((match = chapterRegex.exec(content)) !== null) {
            const chapterTitle = `第${match[1]}章 ${match[2]}`;
            const chapterContent = match[3].trim();
            
            if (chapterContent) {  // 确保章节内容不为空
                // 将内容分段并转换为HTML
                const paragraphs = chapterContent.split('\n').filter(p => p.trim());
                const htmlContent = `
                    <html>
                        <head>
                            <title>${chapterTitle}</title>
                        </head>
                        <body>
                            ${paragraphs.map(p => `<p>${p}</p>`).join('\n')}
                        </body>
                    </html>
                `;
                
                chapters.push({
                    title: chapterTitle,
                    data: htmlContent
                });
                console.log('找到章节:', chapterTitle);
            }
        }

        if (chapters.length === 0) {
            throw new Error('未找到任何有效章节');
        }

        console.log('总共找到章节数:', chapters.length);

        // 准备EPUB选项
        const epubPath = txtFilePath.replace('.txt', '.epub');
        console.log('输出文件路径:', epubPath);
        const bookTitle = path.basename(txtFilePath, '.txt');
        
        // 创建EPUB选项
        const options = {
            title: bookTitle,
            author: 'Unknown',
            publisher: 'TXT to EPUB Converter',
            language: 'zh-CN',
            output: epubPath,
            content: chapters,
            tocTitle: '目录'
        };

        // 生成EPUB文件
        await new Epub(options).promise;
        
        console.log(`转换完成！EPUB文件已保存为: ${epubPath}`);
    } catch (error) {
        console.error('转换过程中发生错误:', error);
        console.error('错误详情:', error.stack);
    }
}